package com.sinodata.bsm.center.web.action.resource;

import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.bean.ResTypeBean;
import com.sinodata.bsm.center.cache.ResFindDefCache;
import com.sinodata.bsm.center.cache.ResTypeCache;
import com.sinodata.bsm.center.engine.resource.find.FindLog;
import com.sinodata.bsm.center.engine.resource.find.FindResBean;
import com.sinodata.bsm.center.engine.resource.find.FindResFactory;
import com.sinodata.bsm.center.engine.resource.find.FindResGroup;
import com.sinodata.bsm.center.engine.resource.find.ResourceFinder;
import com.sinodata.bsm.center.purview.FunctionConstants;
import com.sinodata.bsm.center.purview.UserFunctionValidate;
import com.sinodata.bsm.center.service.resource.AttributeService;
import com.sinodata.bsm.center.service.resource.ResService;
import com.sinodata.bsm.center.util.spring.SpringContextHolder;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.constants.RelationConstants;
import com.sinodata.bsm.common.constants.ResConstants;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.common.vo.ResAttrVal;
import com.sinodata.bsm.common.vo.ResType;

/**
 * 
 * <p>
 * Description: 资源发现逻辑发现动作
 * </p>
 *
 * @author wangyilin
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * Jun 4, 2012 11:26:33 AM          wangyilin        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class ResFindAction extends BaseAction<Res> {
    private Res entity;
    private Long id;
    private Long[] ids;
    @Autowired
    private ResService resService;
    @Autowired
    private AttributeService attributeService;

    @Override
    public String delete() throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public String input() throws Exception {

        return null;
    }

    @Override
    public String list() throws Exception {
        FindResGroup resGroup = FindResFactory.getInstance().getResGroup(this.id);
        List<FindResBean> beanList = resGroup.getAllBeans();
        JSONArray array = new JSONArray();
        JSONObject json = new JSONObject();
        json.element("iTotalRecords", beanList.size());
        json.element("iTotalDisplayRecords", beanList.size());
        for (FindResBean bean : beanList) {
            JSONObject obj = new JSONObject();
            ResTypeBean restype = ResTypeBean.get(bean.getRes().getResTypeId().longValue());
            obj.element("resTypeName", restype.resType().getName());
            obj.element("resname", bean.getRes().getName());
            if (!bean.isChanged()) {
                obj.element("chgStatus", "无变更");
                obj.element("chgContent", "");
                obj.element("chgType", 0);
            } else {

                if (bean.getChangeType() == FindResBean.CHANGE_ADD) {
                    obj.element("chgStatus", "新增");
                } else if (bean.getChangeType() == FindResBean.CHANGE_MOD) {
                    obj.element("chgStatus", "修改");
                } else {
                    obj.element("chgStatus", "删除");
                }
                obj.element("chgType", bean.getChangeType());
                obj.element("chgContent", bean.toChangedString());
            }
            array.add(obj);
        }
        json.element("aaData", array);
        json.element("countUpdate", 999);
        Struts2Utils.renderText(json.toString());

        return null;
    }

    public String view() {
        request.setAttribute("id", id);
        boolean hasPrivilege = UserFunctionValidate.resFunctionValidate(id, FunctionConstants.EDIT_RES);
        Struts2Utils.setRequestAttribute("hasEditResPrivilege", hasPrivilege);
        ResTypeCache resTypeCache = SpringContextHolder.getBean(ResTypeCache.class);
        ResFindDefCache resFindDefCache = SpringContextHolder.getBean(ResFindDefCache.class);
        Res res = resService.get(id);
        ResType resType = resTypeCache.get(res.getResTypeId());
        boolean isFindRes = true;
        if (resType.getFoundFlag() == null || resType.getFoundFlag() == 0) {
            isFindRes = false;
        }
        request.setAttribute("isFindRes", isFindRes);
        return "view";
    }

    public String doFind() {
        logger.info(">>>>>> begin doFind process.resId=" + id);
        JSONObject object = new JSONObject();
        try {
            ResourceFinder.doFind(this.id);
            object.element("dofind", true);
        } catch (Exception e) {
            object.element("dofind", false);
        }

        FindResGroup resGroup = FindResFactory.getInstance().getResGroup(this.id);
        Map<Long, FindLog> logs = resGroup.getFindLogs();

        JSONArray arr = new JSONArray();
        for (Long key : logs.keySet()) {
            JSONObject info = new JSONObject();
            info.element("id", key);
            FindLog log = logs.get(key);
            info.element("status", log.getStatus());
            info.element("msg", log.getMessage());
            arr.add(info);
        }

        object.element("infos", arr);
        Struts2Utils.renderText(object.toString());
        return null;
    }

    public String checkSucces() {
        FindResGroup resGroup = FindResFactory.getInstance().getResGroup(this.id);
        JSONObject object = new JSONObject();
        if (resGroup.isFinish()) {
            object.element("finished", true);
        } else {

            object.element("finished", false);

        }
        Map<Long, FindLog> logs = resGroup.getFindLogs();
        JSONArray arr = new JSONArray();
        for (Long key : logs.keySet()) {
            JSONObject info = new JSONObject();
            info.element("id", key);
            FindLog log = logs.get(key);
            info.element("status", log.getStatus());
            info.element("msg", log.getMessage());
            arr.add(info);
        }
        object.element("infos", arr);
        Struts2Utils.renderText(object.toString());
        return null;
    }

    public String doFindRes() {
        FindResGroup resGroup = FindResFactory.getInstance().getResGroup(this.id);
        List<FindResBean> beanList = resGroup.getAllBeans();
        boolean refreshTree = false;
        for (FindResBean bean : beanList) {
            if (bean.isChanged()) {
                int changeType = bean.getChangeType();
                if (changeType == FindResBean.CHANGE_ADD) {
                    changeAdd(bean);
                    refreshTree = true;
                } else if (changeType == FindResBean.CHANGE_MOD) {
                    changeMod(bean);
                } else if (changeType == FindResBean.CHANGE_DEL) {
                    changeDel(bean);
                    refreshTree = true;
                }
            }
        }
        resGroup.build();
        if (refreshTree) {
            Struts2Utils.renderText("1");
        } else {
            Struts2Utils.renderText("0");
        }

        return null;
    }

    private void changeAdd(FindResBean bean) {
        Res res = bean.getRes();
        res.setHealthStatus(ResConstants.NORMAL_USABLE);
        res.setPaused(ResConstants.RES_NOT_PAUSED);
        List<ResAttrVal> attValList = bean.getChangeAttrValues();
        Long parentResId = bean.getParent().getRes().getId();
        resService.addResource(parentResId, res, attValList, RelationConstants.FORM);
    }

    private void changeMod(FindResBean bean) {
        Res res = bean.getRes();
        List<ResAttrVal> attValList = bean.getChangeAttrValues();
        // ResAttrVal val = resAttrValCache.get(resId, attrId);
        for (ResAttrVal attrVal : attValList) {
            ResAttrVal oldVal = attributeService.getResAttrVal(res.getId(), attrVal.getAttrId());
            ResAttrVal savedVal = null;
            if (oldVal != null) {
                //修改
                oldVal.setAttrValue(attrVal.getAttrValue());
                savedVal = oldVal;
            } else {
                //新增
                attrVal.setResId(res.getId());
                savedVal = attrVal;
            }
            attributeService.saveResAttrVal(savedVal);
        }

    }

    private void changeDel(FindResBean bean) {
        Res res = bean.getRes();
        resService.deleteResource(this.id, res.getId().longValue());
    }

    @Override
    protected void prepareModel() throws Exception {
        if (id == null) {
            entity = new Res();
        } else {
            entity = resService.get(id);
        }

    }

    @Override
    public String save() throws Exception {

        return null;
    }

    @Override
    public Res getModel() {
        return entity;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Long[] getIds() {
        return ids;
    }

    public void setIds(Long[] ids) {
        this.ids = ids;
    }

}
